package ofpof.domain.dao;

import java.util.Date;

import ofpof.database.MongoDatabaseConnectionProvider;
import ofpof.domain.CaptchaToken;
import ofpof.domain.dao.mapper.CaptchaTokenMapper;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Repository
public class CaptchaDao {
	
	
	@Autowired
	private MongoDatabaseConnectionProvider connectionProvider;

	@Autowired
	private CaptchaTokenMapper captchaTokenMapper;

	public CaptchaToken findTokenById(ObjectId captchaId) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection captchaCollection = connection.getCollection("captchatoken");
		BasicDBObject query = new BasicDBObject("_id", captchaId);

		DBObject dbObject = (DBObject) captchaCollection.findOne(query);
		if (dbObject != null) {
			return captchaTokenMapper.fromDbObject(dbObject);
		}
		
		return null;
	}

	public void create(CaptchaToken captchaToken) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection captchaCollection = connection.getCollection("captchatoken");
		DBObject dbObject = captchaTokenMapper.toDbObject(captchaToken);
		captchaCollection.insert(dbObject);
	}

	public void update(CaptchaToken captchaToken) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection captchaCollection = connection.getCollection("captchatoken");
		BasicDBObject query = new BasicDBObject("_id", captchaToken.getId());
		
		captchaCollection.update(query, captchaTokenMapper.toDbObject(captchaToken));
	}

	public void deleteById(ObjectId captchaId) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection captchaCollection = connection.getCollection("captchatoken");
		BasicDBObject query = new BasicDBObject("_id", captchaId);
		captchaCollection.remove(query);
	}

	public void deleteOlderThan(Date boundaryDate) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection captchaCollection = connection.getCollection("captchatoken");
		
		DBObject query = new BasicDBObject();
		query.put("createdon", new BasicDBObject("$lte",boundaryDate));
		captchaCollection.remove(query);
	}

}
